/*
 * PanelWaveletCompress.java
 *
 * Created on 2008年5月7日, 下午2:09
 */

package GUI;

/**
 *
 * @author  littlechild
 */
import Global.Global;
import Manager.Manager;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.*;
public class PanelWaveletCompress extends javax.swing.JPanel {
    Manager manager;
    JFileChooser filechooser=new JFileChooser();
    PanelCavas original=new PanelCavas(null);
    PanelCavas oriWavelet=new PanelCavas(null);;
    PanelCavas diff=new PanelCavas(null);;
    PanelCavas compressed=new PanelCavas(null);;
    Operations.Wavelet.Compressor compressor=new Operations.Wavelet.Compressor();
    String tmpfile="waveletcompress.wcf.bak";
    int maxFactor=100;
    Integer levels[]=new Integer[]{new Integer(1),new Integer(2),new Integer(3),new Integer(4),new Integer(5)};
    /** Creates new form PanelWaveletCompress */
    public PanelWaveletCompress(Manager mg) {
        manager=mg;
        initComponents();
        init();
    }

    public void init() {
        this.scrollPane11.setViewportView(original);
        this.scrollPane12.setViewportView(oriWavelet);
        this.scrollPane13.setViewportView(compressed);
        this.scrollPane14.setViewportView(diff);
        this.jSlider1.setMaximum(maxFactor);
        this.jSlider1.setValue(20);
        this.jSlider1.setMinimum(2);
        original.setImage(manager.operate(Global.opNone, null));
        this.filechooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
        DefaultComboBoxModel cbm=new DefaultComboBoxModel(levels);
        this.jComboBox1.setModel(cbm);
        this.jComboBox1.setSelectedIndex(2);
    }

    private boolean copy(File file, File file0) {
        FileInputStream fin=null;
        FileOutputStream fout=null;
        try {
             fin = new FileInputStream(file);
             fout = new FileOutputStream(file0);
             byte b[]=new byte[1024];
             int len;
             while((len=fin.read(b))!=-1) {
                 fout.write(b, 0, len);
             }
             fin.close();
             fout.close();
             return true;
        } catch (IOException ex) {
            Logger.getLogger(PanelWaveletCompress.class.getName()).log(Level.SEVERE, null, ex);
        }finally {
            try {
                fin.close();
            } catch (IOException ex) {
                Logger.getLogger(PanelWaveletCompress.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return false;
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jSplitPane1.setDividerLocation(0.5);
        jSplitPane2 = new javax.swing.JSplitPane();
        jSplitPane2.setDividerLocation(0.5);
        scrollPane11 = new javax.swing.JScrollPane();
        scrollPane12 = new javax.swing.JScrollPane();
        jSplitPane3 = new javax.swing.JSplitPane();
        jSplitPane3.setDividerLocation(0.5);
        scrollPane13 = new javax.swing.JScrollPane();
        scrollPane14 = new javax.swing.JScrollPane();
        jSlider1 = new javax.swing.JSlider();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jToolBar1 = new javax.swing.JToolBar();
        open = new javax.swing.JButton();
        save = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();

        setPreferredSize(new java.awt.Dimension(600, 600));

        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane1.setPreferredSize(new java.awt.Dimension(600, 600));

        jSplitPane2.setLeftComponent(scrollPane11);
        jSplitPane2.setRightComponent(scrollPane12);

        jSplitPane1.setLeftComponent(jSplitPane2);

        jSplitPane3.setLeftComponent(scrollPane13);
        jSplitPane3.setRightComponent(scrollPane14);

        jSplitPane1.setRightComponent(jSplitPane3);

        jSlider1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jSlider1MouseReleased(evt);
            }
        });
        jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSlider1StateChanged(evt);
            }
        });

        jLabel1.setText("量化精度：");

        jLabel2.setText("0.20");

        jToolBar1.setRollover(true);

        open.setText("打开压缩文件");
        open.setFocusable(false);
        open.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        open.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openActionPerformed(evt);
            }
        });
        jToolBar1.add(open);

        save.setText("保存压缩文件");
        save.setFocusable(false);
        save.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        save.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveActionPerformed(evt);
            }
        });
        jToolBar1.add(save);

        jButton1.setText("预览");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel3.setText("变换级数：");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(12, 12, 12)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1))
                    .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed
        // TODO add your handling code here:
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "wavelet compression files(.wcf)", "wcf");
        filechooser.setFileFilter(filter);
        int returnVal = filechooser.showOpenDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            this.original.setImage(
                    compressor.depress(filechooser.getSelectedFile().getPath()));
            this.oriWavelet.setImage(null);
            this.compressed.setImage(null);
            this.diff.setImage(null);
        }
}//GEN-LAST:event_openActionPerformed

    private void preview() {
        double factor=1/(double)this.jSlider1.getValue();
        int level=((Integer)this.jComboBox1.getSelectedItem()).intValue();
        oriWavelet.setImage(compressor.compress(original.getImage(), factor,level, tmpfile));
        compressed.setImage(compressor.depress(tmpfile));
        diff.setImage(diff(original.getImage(),compressed.getImage()));
        JOptionPane.showMessageDialog(this, "操作完成","操作完成",JOptionPane.INFORMATION_MESSAGE);
    }

    private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
        // TODO add your handling code here:
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "wavelet compression files(.wcf)", "wcf");
        filechooser.setFileFilter(filter);
        filechooser.setSelectedFile(new File("*.wcf"));
        int returnVal = filechooser.showSaveDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            if(compressed.getImage()==null)
                preview();
            filechooser.getSelectedFile().delete();
            System.out.println(filechooser.getSelectedFile().getPath());
            if(!copy(new File(tmpfile),(filechooser.getSelectedFile())))
                JOptionPane.showMessageDialog(this, "Save error","Save error",JOptionPane.ERROR_MESSAGE );
            else
                JOptionPane.showMessageDialog(this, "Save OK","Save OK",JOptionPane.INFORMATION_MESSAGE );
        }
    }//GEN-LAST:event_saveActionPerformed

    private void jSlider1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jSlider1MouseReleased
        // TODO add your handling code here:
        this.jLabel2.setText(String.valueOf(this.jSlider1.getValue()));
        preview();
    }//GEN-LAST:event_jSlider1MouseReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        preview();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider1StateChanged
        // TODO add your handling code here:
        this.jLabel2.setText(String.valueOf(this.jSlider1.getValue()));
    }//GEN-LAST:event_jSlider1StateChanged
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        jSplitPane1.setDividerLocation(0.5);
        jSplitPane2.setDividerLocation(0.5);
        jSplitPane3.setDividerLocation(0.5);
    }
    private BufferedImage diff(BufferedImage image1,BufferedImage image2) {
        assert image1.getWidth()==image2.getWidth() && image1.getHeight()==image2.getHeight();
        BufferedImage returnImage=new BufferedImage(image1.getWidth(),image1.getHeight(),image1.getType());
        for(int i=0;i!=image1.getWidth();++i) {
            for(int j=0;j!=image1.getHeight();++j) {
                int rgb=0;
                rgb=image1.getRGB(i,j)&0xff;
                rgb-=image2.getRGB(i,j)&0xff;
                rgb=rgb<0 ? -rgb: rgb;
                rgb=(rgb)|(rgb<<8)|(rgb<<16);
                returnImage.setRGB(i, j, rgb);
            }
        }
        return returnImage;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JSplitPane jSplitPane3;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton open;
    private javax.swing.JButton save;
    private javax.swing.JScrollPane scrollPane11;
    private javax.swing.JScrollPane scrollPane12;
    private javax.swing.JScrollPane scrollPane13;
    private javax.swing.JScrollPane scrollPane14;
    // End of variables declaration//GEN-END:variables
   
}
